package com.tduck.cloud.form.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.CharUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.tduck.cloud.common.constant.CommonConstants;
import com.tduck.cloud.form.entity.UserFormDataEntity;
import com.tduck.cloud.form.entity.UserFormEntity;
import com.tduck.cloud.form.entity.UserFormItemEntity;
import com.tduck.cloud.form.entity.UserFormLogicEntity;
import com.tduck.cloud.form.entity.enums.FormItemTypeEnum;
import com.tduck.cloud.form.mapper.FormDashboardMapper;
import com.tduck.cloud.form.service.*;
import com.tduck.cloud.form.util.JsonContainsUtils;
import com.tduck.cloud.form.util.MergeMapUtil;
import com.tduck.cloud.form.vo.FormReportVO;
import lombok.RequiredArgsConstructor;

import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author : smalljop
 * @description :
 * @create :  2020/12/31 14:50
 **/
@Service
@RequiredArgsConstructor
public class FormDashboardServiceImpl implements FormDashboardService {

    private final FormDashboardMapper FormDashboardMapper;

    private final UserFormDataService userFormDataService;

    private final UserFormItemService userFormItemService;

    private final UserFormLogicService userFormLogicService;

    private final UserFormService userFormService;


    @Override
    public Collection<FormReportVO.Situation> formReportSituation(String formKey, String queryData, String beginDate, String endDate) {
        List<UserFormDataEntity> serFormDataEntityList = FormDashboardMapper.selectList(
                Wrappers.<UserFormDataEntity>lambdaQuery().eq(UserFormDataEntity::getFormKey, formKey)
                        .eq(UserFormDataEntity::getDeleteFlag, false)
                        .isNotNull(UserFormDataEntity::getOriginalData)
                        .ge(UserFormDataEntity::getTime, beginDate)
                        .lt(UserFormDataEntity::getTime, endDate)
                        .orderByAsc(UserFormDataEntity::getTime));
        List<UserFormDataEntity> jsonContainsAll = JsonContainsUtils.getJsonContainsAll(queryData, serFormDataEntityList);
        Map<String, Long> collect = jsonContainsAll.stream()
                .collect(Collectors.groupingBy(userFormDataEntity ->
                        DateUtil.format(DateUtil.parse(userFormDataEntity.getTime(), DatePattern.NORM_DATE_PATTERN),
                                DatePattern.NORM_DATE_PATTERN), Collectors.counting()));
        List<FormReportVO.Situation> list = collect.entrySet().stream()
                .map(e -> {
                    FormReportVO.Situation situation = new FormReportVO.Situation();
                    situation.setCreateTime(e.getKey().substring(0, 10));
                    situation.setCount(e.getValue().intValue());
                    return situation;
                })
                .collect(Collectors.toList());
        Date now = new Date();
        List<DateTime> dateTimes = DateUtil.rangeToList(DateUtil.beginOfWeek(now), DateUtil.endOfWeek(now), DateField.DAY_OF_WEEK);
        dateTimes.forEach(time -> {
            list.add(new FormReportVO.Situation(time.toString(DatePattern.NORM_DATE_PATTERN), 0));
        });
        return CollectionUtil.sort(list, (o1, o2) -> DateUtil.parse(o1.getCreateTime(), DatePattern.NORM_DATE_PATTERN)
                .isAfter(DateUtil.parse(o2.getCreateTime(), DatePattern.NORM_DATE_PATTERN)) ? 1 : -1);
    }

    @Override
    public Map<String, Integer> formReportPosition(String formKey, String queryData, String beginDate, String endDate) {
        List<UserFormDataEntity> serFormDataEntityList = FormDashboardMapper.selectList(
                Wrappers.<UserFormDataEntity>lambdaQuery().eq(UserFormDataEntity::getFormKey, formKey)
                        .eq(UserFormDataEntity::getDeleteFlag, false)
                        .isNotNull(UserFormDataEntity::getOriginalData)
                        .ge(UserFormDataEntity::getTime, beginDate)
                        .lt(UserFormDataEntity::getTime, endDate));
        List<UserFormDataEntity> jsonContainsAll = JsonContainsUtils.getJsonContainsAll(queryData, serFormDataEntityList);
        Map<String, Long> collect = jsonContainsAll.stream()
                .filter(userFormDataEntity -> ObjectUtil.isNotNull(userFormDataEntity.getSubmitAddress()))
                .collect(Collectors.groupingBy(UserFormDataEntity::getSubmitAddress, Collectors.counting()));
        List<FormReportVO.Position> list = collect.entrySet().stream()
                .map(e -> {
                    FormReportVO.Position situation = new FormReportVO.Position();
                    situation.setSubmitAddress(e.getKey());
                    situation.setCount(e.getValue().intValue());
                    return situation;
                })
                .collect(Collectors.toList());
        return list.stream()
                .filter(item -> ObjectUtil.isNotNull(CollectionUtil.get(StrUtil.split(item.getSubmitAddress(), CharUtil.DASHED), 0)))
                .map(item -> {
                    item.setSubmitProvince(CollectionUtil.get(StrUtil.split(item.getSubmitAddress(), CharUtil.DASHED), 0));
                    return item;
                }).collect(Collectors.groupingBy(FormReportVO.Position::getSubmitProvince,
                        Collectors.summingInt(FormReportVO.Position::getCount)));
    }

    @Override
    public List<FormReportVO.Device> formReportDevice(String formKey, String queryData, String beginDate, String endDate) {
        List<FormReportVO.Device> list = new ArrayList<>();
        List<UserFormDataEntity> serFormDataEntityList = FormDashboardMapper.selectList(
                Wrappers.<UserFormDataEntity>lambdaQuery().eq(UserFormDataEntity::getFormKey, formKey)
                        .eq(UserFormDataEntity::getDeleteFlag, false)
                        .isNotNull(UserFormDataEntity::getOriginalData)
                        .ge(UserFormDataEntity::getTime, beginDate)
                        .lt(UserFormDataEntity::getTime, endDate));
        List<UserFormDataEntity> jsonContainsAll = JsonContainsUtils.getJsonContainsAll(queryData, serFormDataEntityList);
        Map<String, Long> collect = jsonContainsAll.stream()
                .filter(userFormDataEntity -> ObjectUtil.isNotNull(userFormDataEntity.getSubmitOs()))
                .collect(Collectors.groupingBy(UserFormDataEntity::getSubmitOs, Collectors.counting()));
        collect.forEach((k, v) -> {
            FormReportVO.Device source = new FormReportVO.Device();
            source.setOsName(k);
            source.setCount(v.intValue());
            list.add(source);
        });
        return list;
    }

    @Override
    public List<FormReportVO.Source> formReportSource(String formKey, String queryData, String beginDate, String endDate) {
        List<FormReportVO.Source> list = new ArrayList<>();
        List<UserFormDataEntity> serFormDataEntityList = FormDashboardMapper.selectList(
                Wrappers.<UserFormDataEntity>lambdaQuery().eq(UserFormDataEntity::getFormKey, formKey)
                        .eq(UserFormDataEntity::getDeleteFlag, false)
                        .isNotNull(UserFormDataEntity::getOriginalData)
                        .ge(UserFormDataEntity::getTime, beginDate)
                        .lt(UserFormDataEntity::getTime, endDate));
        List<UserFormDataEntity> jsonContainsAll = JsonContainsUtils.getJsonContainsAll(queryData, serFormDataEntityList);
        Map<String, Long> collect = jsonContainsAll.stream()
                .filter(userFormDataEntity -> ObjectUtil.isNotNull(userFormDataEntity.getSubmitBrowser()))
                .collect(Collectors.groupingBy(UserFormDataEntity::getSubmitBrowser, Collectors.counting()));
        collect.forEach((k, v) -> {
            FormReportVO.Source source = new FormReportVO.Source();
            source.setBrowserName(k);
            source.setCount(v.intValue());
            list.add(source);
        });
        return list;
    }

    @Override
    public List<FormReportVO.Analysis> formReportAnalysis(String formKey, String queryData, String beginDate, String endDate) {
        List<FormItemTypeEnum> typeEnumList = Lists.newArrayList(
                FormItemTypeEnum.RADIO,
                FormItemTypeEnum.CHECKBOX,
                FormItemTypeEnum.IMAGE_SELECT,
                FormItemTypeEnum.SELECT
        );
        List<FormItemTypeEnum> typeEnumList2 = Lists.newArrayList(
                FormItemTypeEnum.MATRIX_SELECT
        );
        // 题目
        List<UserFormItemEntity> formItemList = userFormItemService.list(new QueryWrapper<UserFormItemEntity>()
                .lambda().eq(UserFormItemEntity::getFormKey, formKey).orderByAsc(UserFormItemEntity::getSort));

//        List<Map<String, Map<Integer, Object>>> collect = new ArrayList<>();
        Map<String, List<Map<String, Object>>> collect = formItemList.stream()
                // 过滤符合条件的 item
                .filter(item -> FormItemTypeEnum.MATRIX_SELECT.equals(item.getType()))
                // 提取 formItemId 和 scheme, 并安全地从中获取 table 和 rows
                .collect(Collectors.toMap(
                        UserFormItemEntity::getFormItemId,  // 将 formItemId 作为 key
                        item -> {
                            // 提取 scheme, 获取 table 中的 rows
                            Map<String, Object> scheme = item.getScheme();
                            Map<String, Object> table = (Map<String, Object>) scheme.get("table");
                            List<Map<String, Object>> rows = (List<Map<String, Object>>) table.get("rows");
                            return rows.stream()
                                    .map(row -> {
                                        // 使用 HashMap 构建外层 Map
                                        Map<String, Object> outerMap = new HashMap<>();
                                        outerMap.put(row.get("id").toString(), row.get("label").toString());
                                        return outerMap;
                                    })
                                    .collect(Collectors.toList());  // 返回转换后的 rows 列表
                        }
                ));


        Map<String, List<Map<String, Object>>> columns = formItemList.stream()
                // 过滤符合条件的 item
                .filter(item -> FormItemTypeEnum.MATRIX_SELECT.equals(item.getType()))
                // 提取 formItemId 和 scheme, 并安全地从中获取 table 和 rows
                .collect(Collectors.toMap(
                        UserFormItemEntity::getFormItemId,  // 将 formItemId 作为 key
                        item -> {
                            // 提取 scheme, 获取 table 中的 rows
                            Map<String, Object> scheme = item.getScheme();
                            Map<String, Object> table = (Map<String, Object>) scheme.get("table");
                            List<Map<String, Object>> rows = (List<Map<String, Object>>) table.get("columns");
                            return rows.stream()
                                    .map(row -> {
                                        // 使用 HashMap 构建外层 Map
                                        Map<String, Object> outerMap = new HashMap<>();
                                        outerMap.put(row.get("id").toString(), row.get("label").toString());
                                        return outerMap;
                                    })
                                    .collect(Collectors.toList());  // 返回转换后的 rows 列表
                        }
                ));

        // 结果
        List<UserFormDataEntity> allFormResultList = userFormDataService.list(new QueryWrapper<UserFormDataEntity>().lambda()
                .eq(UserFormDataEntity::getFormKey, formKey)
                .eq(UserFormDataEntity::getDeleteFlag, false)
                .isNotNull(UserFormDataEntity::getOriginalData)
                .ge(ObjectUtil.isNotNull(beginDate), UserFormDataEntity::getTime, beginDate)
                .lt(ObjectUtil.isNotNull(endDate), UserFormDataEntity::getTime, endDate));
        List<UserFormDataEntity> formResultList = JsonContainsUtils.getJsonContainsAll(queryData, allFormResultList);
        // 标题label与id的对应值
        Map<String, FormReportVO.Analysis> formMap = new LinkedHashMap<>();
        // 储存标题与可选项
        List<String> idList = new ArrayList<>();
        List<String> idList2 = new ArrayList<>();
        List<Map<String, Map<String, Integer>>> returnList = new ArrayList<>();
        for (UserFormItemEntity userFormItemEntity : formItemList) {
            if (typeEnumList.contains(userFormItemEntity.getType())) {
                // id and label
                FormReportVO.Analysis analysis = new FormReportVO.Analysis();
//                analysis.setFormItemId(userFormItemEntity.getFormItemId());
                analysis.setLabel(userFormItemEntity.getLabel());
                analysis.setType(userFormItemEntity.getType().getDesc());
                formMap.put(userFormItemEntity.getFormItemId(), analysis);
                idList.add(userFormItemEntity.getFormItemId());
            }
            if (typeEnumList2.contains(userFormItemEntity.getType())) {
                // Create the analysis object
                FormReportVO.Analysis analysis = new FormReportVO.Analysis();
                analysis.setLabel(userFormItemEntity.getLabel());
                analysis.setType(userFormItemEntity.getType().getDesc());

                // Retrieve the data only once
                List<Map<String, Object>> maps = collect.get(userFormItemEntity.getFormItemId());
                List<Map<String, Object>> maps3 = columns.get(userFormItemEntity.getFormItemId());

                // Prepare map for analysis
                Map<String, Map<String, Integer>> map = new HashMap<>();

                // Fill map1 with all possible values from maps3
                Map<String, Integer> map1 = new HashMap<>();
                for (Map<String, Object> objectMap : maps3) {
                    for (Map.Entry<String, Object> objectEntry : objectMap.entrySet()) {
                        String value1 = (String) objectEntry.getValue();
                        map1.put(value1, 0);
                    }
                }

                // Process the maps to construct the final data structure
                for (Map<String, Object> integerObjectMap : maps) {
                    for (Map.Entry<String, Object> integerObjectEntry : integerObjectMap.entrySet()) {
                        String value = (String) integerObjectEntry.getValue();
                        map.put(value, new HashMap<>(map1));  // Copy the structure for each value
                    }
                }

                // Add the final map to the return list and set matrix data
                returnList.add(map);
                analysis.setMatrixData(returnList);
                analysis.setChartType(null);
//                analysis.setFormItemId(userFormItemEntity.getFormItemId());
//
                // Store the result in formMap
                formMap.put(userFormItemEntity.getFormItemId(), analysis);

                // Add the form item ID to idList2
                idList2.add(userFormItemEntity.getFormItemId());
            }

        }
        System.out.println("collect==" + collect);
        System.out.println("columns==" + columns);
        System.out.println("idList2==" + idList2);
        System.out.println("formMap==" + formMap);

        for (UserFormDataEntity userFormResultEntity : formResultList) {
            Map<String, Object> originalData = userFormResultEntity.getOriginalData();
            for (String fieldId : idList) {
                Map<String, Integer> labelCountMap = formMap.get(fieldId).getMap();
                if (ObjectUtil.isNull(labelCountMap)) {
                    labelCountMap = Maps.newHashMap();
                }
                if (originalData.containsKey(fieldId)) {
                    // 结果中字段值  处理多选
                    if (originalData.get(fieldId) instanceof Collection) {
                        List<Object> fieldValues = MapUtil.get(originalData, fieldId, List.class);
                        List<String> fieldLabelValues = MapUtil.get(originalData, fieldId + "label", List.class);
                        for (int i = 0; i < fieldValues.size(); i++) {
                            // 是否是其他输入
                            Object value = fieldValues.get(i);
                            String label = value.equals(CommonConstants.ConstantNumber.ZERO) ? "其他" : fieldLabelValues.get(i);
                            Integer count = labelCountMap.get(label);
                            labelCountMap.put(label.trim(), ObjectUtil.isNotNull(count) ? count + 1 : 1);
                        }
                    } else {
                        String label = MapUtil.getStr(originalData, fieldId + "label");
                        Integer count = labelCountMap.get(label);
                        labelCountMap.put(label, ObjectUtil.isNotNull(count) ? count + 1 : 1);
                    }
                }
                formMap.get(fieldId).setFieldName(labelCountMap.keySet());
                formMap.get(fieldId).setData(labelCountMap.values());
                formMap.get(fieldId).setMap(labelCountMap);
            }
            for (String fieldId : idList2) {
                System.out.println("fieldId==" + fieldId);
                List<Map<String, Map<String, Integer>>> matrixData = formMap.get(fieldId).getMatrixData();
                if (originalData.containsKey(fieldId)) {
                    if (originalData.get(fieldId) instanceof Map) {
                        Map<String, String> map = MapUtil.get(originalData, fieldId, Map.class);
                        for (Map.Entry<String, String> o : map.entrySet()) {
                            String key = o.getKey();
                            String value = o.getValue();
                            System.out.println("key=="+key);
                            System.out.println("value=="+value);
                            for (Map.Entry<String, List<Map<String, Object>>> stringListEntry : collect.entrySet()) {
                                String key1 = stringListEntry.getKey();
                                System.out.println("key1=="+key1);
                                List<Map<String, Object>> value1 = stringListEntry.getValue();
                                System.out.println("value1=="+value1.toString());
                                for (Map<String, Object> integerObjectMap : value1) {
                                    System.out.println("integerObjectMap"+integerObjectMap);
                                    for (Map<String, Map<String, Integer>> matrixDatum : matrixData) {
                                        for (Map.Entry<String, Map<String, Integer>> stringMapEntry : matrixDatum.entrySet()) {
                                            System.out.println(integerObjectMap.get(key));
                                            System.out.println(stringMapEntry.getKey());
                                            if(stringMapEntry.getKey().equals(integerObjectMap.get(key))){
                                                Map<String, Integer> value2 = stringMapEntry.getValue();
                                                value2.put(value, ObjectUtil.isNotNull(value2.get(value)) ? value2.get(value) + 1 : 1);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                formMap.get(fieldId).setMatrixData(matrixData);
            }
        }
        List<FormReportVO.Analysis> result = new ArrayList(formMap.values());
        return result;
    }

    @Override
    public List<Map<String, Object>> formReportSatisfaction(String formKey, String queryData, String beginDate, String endDate) {
        List<Map<String, Object>> returnListMap = new ArrayList<Map<String, Object>>();

        // 获取满意度配置
        UserFormEntity userFormEntity = userFormService.getByKey(formKey);
        Map<String, Object> formSetting = userFormEntity.getFormSetting();
        Map<String, Integer> satisfactionScoreMap = new HashMap<>();
        if (ObjectUtil.isEmpty(formSetting)) {
            satisfactionScoreMap.put("很满意", 5);
            satisfactionScoreMap.put("满意", 4);
            satisfactionScoreMap.put("一般满意", 3);
            satisfactionScoreMap.put("不满意", 2);
            satisfactionScoreMap.put("很不满意", 1);
        } else {
            Map<String, Integer> mydList = (Map<String, Integer>) formSetting.get("satisfaction");
            mydList.entrySet().stream()
                    .filter(entry -> entry.getValue() != 0)
                    .forEach(entry -> satisfactionScoreMap.put(entry.getKey(), entry.getValue()));
        }
        List<FormItemTypeEnum> typeEnumList = Lists.newArrayList(
                FormItemTypeEnum.RADIO,
                FormItemTypeEnum.CHECKBOX,
                FormItemTypeEnum.IMAGE_SELECT,
                FormItemTypeEnum.SELECT
        );
        // 题目
        List<UserFormItemEntity> formItemList = userFormItemService.list(new QueryWrapper<UserFormItemEntity>().lambda().eq(UserFormItemEntity::getFormKey, formKey).orderByAsc(UserFormItemEntity::getSort));
        // 结果
        List<UserFormDataEntity> allFormResultList = userFormDataService.list(Wrappers.<UserFormDataEntity>lambdaQuery().eq(UserFormDataEntity::getFormKey, formKey)
                .eq(UserFormDataEntity::getDeleteFlag, false)
                .isNotNull(UserFormDataEntity::getOriginalData)
                .ge(ObjectUtil.isNotNull(beginDate), UserFormDataEntity::getTime, beginDate)
                .lt(ObjectUtil.isNotNull(endDate), UserFormDataEntity::getTime, endDate));
        // 合计权重
        int totalWeight = 0;
        List<UserFormDataEntity> formResultList = JsonContainsUtils.getJsonContainsAll(queryData, allFormResultList);
        //通过formkey，获取到问题List
        for (UserFormItemEntity UserFormItemCheck : formItemList) {
            Map<String, Object> schemeCheckMap = UserFormItemCheck.getScheme();
            Map<String, Object> configCheckMap = (Map<String, Object>) schemeCheckMap.get("config");
            Map<String, Object> questionCheckMap = new HashMap<>();
            //通过遍历获取check_title不为空的问题；例如：临床科室
            if (!StringUtils.isEmpty(configCheckMap.get("check_title"))) {
                List<Map<String, Object>> optionsCheckMapList = (List<Map<String, Object>>) configCheckMap.get("options");
                //拿到考核标题，对应的options，例如：A科室、B科室、C科室
                for (Map<String, Object> optionsCheckMap : optionsCheckMapList) {
                    Map<String, Object> returnMap = new HashMap<>();
                    returnMap.put("checkTitle", optionsCheckMap.get("label"));
                    // returnMap.put("formKey", schemeCheckMap.get("key"));
                    returnMap.put("formKey", UserFormItemCheck.getFormKey());
//                    int count = userFormDataService.count(Wrappers.<UserFormDataEntity>lambdaQuery().eq(UserFormDataEntity::getFormKey, UserFormItemCheck.getFormKey())
//                            .eq(UserFormDataEntity::getDeleteFlag, false)
//                            .like(UserFormDataEntity::getOriginalData, optionsCheckMap.get("label").toString().trim())
//                            .ge(ObjectUtil.isNotNull(beginDate), UserFormDataEntity::getTime, beginDate)
//                            .lt(ObjectUtil.isNotNull(endDate), UserFormDataEntity::getTime, endDate));
                    // returnMap.put("total", count);
                    List<Map<String, Object>> questionListMap = new ArrayList<Map<String, Object>>();
                    //循环获取统计标题
                    int itemIndex = 0;
                    for (UserFormItemEntity UserFormItem : formItemList) {
                        itemIndex++;
                        Map<String, Object> schemeMap = UserFormItem.getScheme();
                        Map<String, Object> configMap = (Map<String, Object>) schemeMap.get("config");
                        Map<String, Object> questionMap = new HashMap<>();
                        if (ObjectUtil.isNotNull(configMap.get("options"))) {
                            //获取非考核标题之外的考核标题（对应数字）
                            if (StringUtils.isEmpty(configMap.get("check_title")) && Arrays.asList(configCheckMap.get("check_question").toString().split(",")).contains(String.valueOf(itemIndex))) {
                                List<Map<String, Object>> optionsMapList = (List<Map<String, Object>>) configMap.get("options");

                                Map<String, Integer> questionOptionsMap = new HashMap<>();
                                questionMap.put("formItemLabel", configMap.get("label"));
                                questionMap.put("formItemId", configMap.get("formId"));

                                if (ObjectUtil.isNotNull(configMap.get("satisfactionWeight")) && ObjectUtil.isNotEmpty(configMap.get("satisfactionWeight")) && Integer.parseInt(configMap.get("satisfactionWeight").toString()) != 0) {
                                    questionMap.put("satisfactionWeight", configMap.get("satisfactionWeight"));
                                } else if (ObjectUtil.isNull(configMap.get("satisfactionWeight")) || ObjectUtil.isEmpty(configMap.get("satisfactionWeight"))) {
                                    questionMap.put("satisfactionWeight", 100);
                                }
                                int i = 0;
                                //循环遍历
                                for (Map<String, Object> optionsMap : optionsMapList) {
                                    i++;
                                    //遍历数据，看对应项目有多少数据
                                    for (UserFormDataEntity userFormResultEntity : formResultList) {
                                        Map<String, Object> originalData = userFormResultEntity.getOriginalData();
                                        if (ObjectUtil.isNotEmpty(originalData.get(configMap.get("formId")))) {
                                            Integer index = (Integer) originalData.get(configMap.get("formId"));
                                            if (questionOptionsMap.containsKey(optionsMap.get("label"))) {
                                                //判断数据中的考核标题和循环中的考核标题对比，对比一直则数据+1
                                                if (originalData.get(configCheckMap.get("formId").toString() + "label").equals(optionsCheckMap.get("label")) && index == optionsMap.get("value")) {
                                                    questionOptionsMap.put((String) optionsMap.get("label"), questionOptionsMap.get((String) optionsMap.get("label")) + 1);
                                                }
                                            } else {
                                                if (originalData.get(configCheckMap.get("formId").toString() + "label").equals(optionsCheckMap.get("label")) && index == optionsMap.get("value")) {
                                                    questionOptionsMap.put((String) optionsMap.get("label"), 1);
                                                } else {
                                                    questionOptionsMap.put((String) optionsMap.get("label"), 0);
                                                }

                                            }
                                        }
                                    }
                                    questionMap.put("map", questionOptionsMap);
                                }

                                //问题满意度
                                int totalScore = 0;
                                int totalNum = 0;
                                Map<String, Integer> map = (Map<String, Integer>) questionMap.get("map");
                                for (String key : map.keySet()) {
                                    if (satisfactionScoreMap.containsKey(key)) {
                                        totalNum += map.get(key);
                                        int satisfactionScore = satisfactionScoreMap.get(key);
                                        totalScore += map.get(key) * satisfactionScore;
                                    }
                                }
                                if (totalNum > 0) {
                                    double satisfaction = (double) totalScore / 5 / totalNum * 100.00;
                                    questionMap.put("satis", satisfaction);
                                    questionMap.put("satisfaction", String.format("%.2f%%", satisfaction));
                                } else {
                                    questionMap.put("satis", 0);
                                    questionMap.put("satisfaction", "0.0%");
                                }
                                questionListMap.add(questionMap);
                            }
                        }
                    }
                    // 科室满意度
                    int weightSum = 0;
                    double statis = 0.0;
                    Map<String, Integer> satisfactionMap = new HashMap<>();

                    for (Map<String, Object> map : questionListMap) {
                        @SuppressWarnings("unchecked")
                        Map<String, Integer> station = (Map<String, Integer>) map.get("map");
                        if (!station.isEmpty()) {
                            for (Map.Entry<String, Integer> entry : station.entrySet()) {
                                satisfactionMap.put(entry.getKey(), satisfactionMap.getOrDefault(entry.getKey(), 0) + entry.getValue());
                            }

                            int satisfactionWeight = Integer.parseInt(map.get("satisfactionWeight").toString());
                            double satisValue = Double.parseDouble(map.get("satis").toString());

                            weightSum += satisfactionWeight;
                            statis += satisValue * satisfactionWeight;
                        }
                    }

                    totalWeight += weightSum;

                    returnMap.put("satisfactionMap", satisfactionMap);
                    double ratio = statis / weightSum;
                    returnMap.put("satisfaction", String.format("%.2f%%", ratio));
                    returnMap.put("question", questionListMap);
                    returnListMap.add(returnMap);
                }
            }
        }
        Map<String, Object> allMap = new HashMap<>();
        Map<String, Integer> mydMap = new HashMap<>();
        returnListMap.forEach(map -> {
            Map<String, Integer> satisfactionMap = (Map<String, Integer>) map.get("satisfactionMap");
            satisfactionMap.forEach((key, num) -> {
                if (satisfactionScoreMap.containsKey(key)) {
                    mydMap.compute(key, (k, v) -> v != null ? v + num : num);
                }
            });
        });
        int allScore = 0;
        int allTotal = 0;
        for (Map.Entry<String, Integer> entry : mydMap.entrySet()) {
            String key = entry.getKey();
            Integer value = entry.getValue();
            if (satisfactionScoreMap.containsKey(key)) {
                Integer integer = satisfactionScoreMap.get(key);
                allScore += integer * value;
                allTotal += value;
            }
        }
        double ratio = (double) allScore / 5 / allTotal * 100.0;
        allMap.put("satisfaction", String.format("%.2f%%", ratio));
        allMap.put("checkTitle", "合计");
//        allMap.put("totalWeight", totalWeight);
        allMap.put("satisfactionMap", mydMap);
        returnListMap.add(allMap);
        return returnListMap;
    }

    @Override
    public List<Map<String, Object>> formReportMedicalSkill(String type, String formKey, String queryData, String beginDate, String endDate) {
        List<Map<String, Object>> returnListMap = new ArrayList<Map<String, Object>>();

        // 获取满意度配置
        UserFormEntity userFormEntity = userFormService.getByKey(formKey);
        Map<String, Object> formSetting = userFormEntity.getFormSetting();

        List<UserFormItemEntity> formItemList = userFormItemService.list(new QueryWrapper<UserFormItemEntity>().lambda().eq(UserFormItemEntity::getFormKey, formKey)
                .orderByAsc(UserFormItemEntity::getSort));
        // 结果
        List<UserFormDataEntity> allFormResultList = userFormDataService.list(Wrappers.<UserFormDataEntity>lambdaQuery()
                .eq(UserFormDataEntity::getFormKey, formKey)
                .eq(UserFormDataEntity::getDeleteFlag, false)
                .isNotNull(UserFormDataEntity::getOriginalData)
                .ge(ObjectUtil.isNotNull(beginDate), UserFormDataEntity::getTime, beginDate)
                .lt(ObjectUtil.isNotNull(endDate), UserFormDataEntity::getTime, endDate));
        List<UserFormDataEntity> formResultList = JsonContainsUtils.getJsonContainsAll(queryData, allFormResultList);
        List<UserFormLogicEntity> userFormLogicList = userFormLogicService.list(new QueryWrapper<UserFormLogicEntity>().lambda()
                .eq(UserFormLogicEntity::getFormKey, formKey));
        // 对应关系集合
        List<Map<String, Object>> correspondenceList = new ArrayList();
        for (int i = 0; i < userFormLogicList.size(); i++) {
            List<UserFormLogicEntity.Definition> scheme = userFormLogicList.get(i).getScheme();
            Map<String, Object> map = new HashMap<>();
            for (int j = 0; j < scheme.size(); j++) {
                Map<String, Object> schemeMap = (Map<String, Object>) scheme.get(j);
                if (Integer.parseInt(schemeMap.get("expression").toString()) == 1) {
                    String checkboxId = (String) schemeMap.get("formItemId");
                    String radioId = null;
                    List<Map<String, Object>> list2 = (List<Map<String, Object>>) schemeMap.get("conditionList");
                    if (ObjectUtil.isNotNull(list2)) {
                        for (int x = 0; x < list2.size(); x++) {
                            radioId = (String) list2.get(x).get("formItemId");
                        }
                    }
                    if (ObjectUtil.isNotNull(radioId)) {
                        map.put(radioId, checkboxId);
                    }
                }
            }
            correspondenceList.add(map);
        }
        List<String> serviceOptionsList = new ArrayList<>();
        List<String> mydOptionsList = new ArrayList<>();
        for (UserFormItemEntity userFormItem : formItemList) {
            Map<String, Object> schemeMap = userFormItem.getScheme();
            Map<String, Object> configMap = (Map<String, Object>) schemeMap.get("config");
            // 获取所有的多选选项数据
            if (ObjectUtil.isNotNull(configMap.get("tag"))) {
                if ("t-checkbox-group".equals(configMap.get("tag"))) {
                    List<Map<String, Object>> list = (List<Map<String, Object>>) configMap.get("options");
                    for (int i = 0; i < list.size(); i++) {
                        Object label = list.get(i).get("label");
                        if (!serviceOptionsList.contains((String) label)) {
                            serviceOptionsList.add((String) label);
                        }
                    }
                }
            }
            // 获取所有的单选选项数据
            if ("t-radio-group".equals(configMap.get("tag"))) {
                List<Map<String, Object>> list = (List<Map<String, Object>>) configMap.get("options");
                for (int i = 0; i < list.size(); i++) {
                    Object label = list.get(i).get("label");
                    mydOptionsList.add((String) label);
                }
            }
        }
        for (UserFormItemEntity userFormItem : formItemList) {
            Map<String, Object> schemeMap = userFormItem.getScheme();
            Map<String, Object> configMap = (Map<String, Object>) schemeMap.get("config");
            // 返回的map,组织对比数据
            LinkedHashMap<String, Object> satisfaction = new LinkedHashMap<>();
            if ("t-checkbox-group".equals(configMap.get("tag")) || "t-radio-group".equals(configMap.get("tag"))) {
                // 科室
                if ("statistics_one".equals(type)) {
                    if (ObjectUtil.isNotNull(configMap.get("statistics_one"))) {
                        satisfaction.put("name", configMap.get("statistics_one"));
                    }
                } else if ("statistics_two".equals(type)) {
                    if (ObjectUtil.isNotNull(configMap.get("statistics_two"))) {
                        satisfaction.put("name", configMap.get("statistics_two"));
                    }
                } else if ("statistics_three".equals(type)) {
                    if (ObjectUtil.isNotNull(configMap.get("statistics_three"))) {
                        satisfaction.put("name", configMap.get("statistics_three"));
                    }
                } else if (ObjectUtil.isEmpty(type)) {
                    if (ObjectUtil.isNotNull(configMap.get("label")) && "t-radio-group".equals(configMap.get("tag"))) {
                        satisfaction.put("name", configMap.get("label"));
                    }
                }
                if (ObjectUtil.isNotNull(configMap.get("satisfactionWeight")) && ObjectUtil.isNotEmpty(configMap.get("satisfactionWeight")) && Integer.parseInt(configMap.get("satisfactionWeight").toString()) != 0) {
                    satisfaction.put("satisfactionWeight", configMap.get("satisfactionWeight"));
                } else if (ObjectUtil.isNull(configMap.get("satisfactionWeight")) || ObjectUtil.isEmpty(configMap.get("satisfactionWeight"))) {
                    satisfaction.put("satisfactionWeight", 100);
                }
                satisfaction.put("question", configMap.get("label"));
                satisfaction.put(configMap.get("formId") + "label", configMap.get("formId"));
                satisfaction.put("formId", configMap.get("formId"));

                if (ObjectUtil.isNotEmpty(correspondenceList)) {
                    for (int i = 0; i < correspondenceList.size(); i++) {
                        for (String key2 : satisfaction.keySet()) {
                            if ("formId".equals(key2)) {
                                if (ObjectUtil.isNotNull(correspondenceList.get(i).get(satisfaction.get("formId")))) {
                                    satisfaction.put((String) correspondenceList.get(i).get(satisfaction.get("formId")), satisfaction.get("formId"));
                                }
                            }
                        }
                    }
                }
                for (int i = 0; i < mydOptionsList.size(); i++) {
                    LinkedHashMap<String, Object> optionsMap = new LinkedHashMap<>();
                    if (ObjectUtil.isNotEmpty(serviceOptionsList)) {
                        if ("很满意".equals(mydOptionsList.get(i))) {
                            optionsMap.put("总数量", 0);
                        } else {
                            optionsMap.put("总数量", 0);
                            for (int j = 0; j < serviceOptionsList.size(); j++) {
                                optionsMap.put(serviceOptionsList.get(j), 0);
                            }
                        }
                        satisfaction.put(mydOptionsList.get(i), optionsMap);
                    } else {
                        satisfaction.put(mydOptionsList.get(i), 0);
                    }
                }
            }

            if (ObjectUtil.isNotEmpty(satisfaction.get("name"))) {
                if (ObjectUtil.isNotNull(formResultList)) {
                    for (UserFormDataEntity userFormDataEntity : formResultList) {
                        // 填写的数据集
                        Map<String, Object> originalData = userFormDataEntity.getOriginalData();
                        for (String key : originalData.keySet()) {
                            // 单选数据处理
                            if (key.startsWith("radio") && key.endsWith("label")) {
                                for (String key2 : satisfaction.keySet()) {
                                    if (key.equals(key2)) {
                                        for (String key3 : satisfaction.keySet()) {
                                            if (originalData.get(key).equals(key3)) {
                                                if (ObjectUtil.isNotEmpty(serviceOptionsList)) {
                                                    Map<String, Integer> map = (Map<String, Integer>) satisfaction.get(key3);
                                                    map.put("总数量", map.get("总数量") + 1);
                                                    LinkedHashMap<String, Integer> map2 = new LinkedHashMap<>(map);
                                                    satisfaction.put(key3, map2);
                                                } else {
                                                    satisfaction.put(key3, (Integer) satisfaction.get(key3) + 1);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            if (ObjectUtil.isNotEmpty(serviceOptionsList)) {
                                //  如果服务选项列表不为空
                                if (key.startsWith("checkbox") && key.endsWith("label")) {
                                    // 多选数据处理
                                    if (key.startsWith("checkbox") && key.endsWith("label")) {
                                        Object str = originalData.get(key);
                                        String replace = str.toString().replace("[", "").replace("]", "").replace(" ", "");
                                        String[] split = replace.split(",");
                                        List<String> data = new ArrayList<>(Arrays.asList(split));
                                        for (String key2 : satisfaction.keySet()) {
                                            if ((key2 + "label").equals(key)) {
                                                Map<String, Integer> map = (Map<String, Integer>) satisfaction.get(originalData.get(satisfaction.get(key2) + "label"));
                                                for (String key5 : map.keySet()) {
                                                    for (int i = 0; i < data.size(); i++) {
                                                        if (data.get(i).equals(key5)) {
                                                            map.put(key5, map.get(key5) + 1);
                                                            LinkedHashMap<String, Integer> map2 = new LinkedHashMap<>(map);
                                                            satisfaction.put((String) originalData.get(satisfaction.get(key2) + "label"), map2);
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            // 临时数据
            satisfaction.remove(configMap.get("formId") + "label");
            for (int i = 0; i < correspondenceList.size(); i++) {
                satisfaction.remove(correspondenceList.get(i).get(satisfaction.get("formId")));
            }
            satisfaction.remove("formId");
            if (ObjectUtil.isNotEmpty(satisfaction.get("name"))) {
                if (ObjectUtil.isNull(configMap.get("satisfactionWeight")) || ObjectUtil.isEmpty(configMap.get("satisfactionWeight")) || Integer.parseInt(configMap.get("satisfactionWeight").toString()) != 0) {
                    returnListMap.add(satisfaction);
                }
            }
        }

        //  声明服务选项列表是否为空
        boolean hasServiceOptions = ObjectUtil.isNotEmpty(serviceOptionsList);
        Map<String, Integer> satisfactionScoreMap = new HashMap<>();
        if (ObjectUtil.isEmpty(formSetting)) {
            satisfactionScoreMap.put("很满意", 5);
            satisfactionScoreMap.put("满意", 4);
            satisfactionScoreMap.put("一般满意", 3);
            satisfactionScoreMap.put("不满意", 2);
            satisfactionScoreMap.put("很不满意", 1);
        } else {
            Map<String, Integer> mydList = (Map<String, Integer>) formSetting.get("satisfaction");
            mydList.entrySet().stream()
                    .filter(entry -> entry.getValue() != 0)
                    .forEach(entry -> satisfactionScoreMap.put(entry.getKey(), entry.getValue()));
        }
        for (Map<String, Object> currentMap : returnListMap) {
            //总满意度分值
            int totalScore = 0;
            //总问卷数量
            int totalNum = 0;
            // 权重值
            int satisfactionWeight = 0;
            if (ObjectUtil.isNotNull(currentMap.get("satisfactionWeight")) && ObjectUtil.isNotEmpty(currentMap.get("satisfactionWeight")) && Integer.parseInt(currentMap.get("satisfactionWeight").toString()) != 0) {
                satisfactionWeight = Integer.parseInt(currentMap.get("satisfactionWeight").toString());
            } else if (ObjectUtil.isNull(currentMap.get("satisfactionWeight")) || ObjectUtil.isEmpty(currentMap.get("satisfactionWeight"))) {
                satisfactionWeight = 100;
            }
            for (String key : currentMap.keySet()) {
                if ("未接触".equals(key)) {
                    continue;
                }
                //如果是满意度选项
                if (satisfactionScoreMap.containsKey(key)) {
                    int satisfactionScore = satisfactionScoreMap.get(key);
                    //如果有服务选项
                    if (hasServiceOptions && currentMap.get(key) instanceof Map) {
                        Map<String, Integer> map = (Map<String, Integer>) currentMap.get(key);
                        totalScore += map.get("总数量") * satisfactionScore * satisfactionWeight;
                        totalNum += map.get("总数量");
                    } else {  //如果没有服务选项
                        totalScore += (Integer) currentMap.get(key) * satisfactionScore * satisfactionWeight;
                        totalNum += (Integer) currentMap.get(key);
                    }
                }
            }
            double ratio = (double) totalScore / satisfactionWeight / 5 / totalNum;
            currentMap.put("satisfaction", ratio);
            currentMap.put("totalNum", totalNum);
        }
        // 根据name值合并数据
        List<Map<String, Object>> resultList = new ArrayList<>();
        for (Map<String, Object> currentMap : returnListMap) {
            String name = (String) currentMap.get("name");
            boolean found = false;
            for (int j = 0; j < resultList.size(); j++) {
                Map<String, Object> resultMap = resultList.get(j);
                if (resultMap.get("name").equals(name)) {
                    MergeMapUtil.mergeMap(resultMap, currentMap, hasServiceOptions, mydOptionsList);
                    found = true;
                    break;
                }
            }
            if (!found) {
                resultList.add(currentMap);
            }
        }
        for (int i = 0; i < resultList.size(); i++) {
            Map<String, Object> map = resultList.get(i);
            if (Integer.parseInt(map.get("totalNum").toString()) == 0) {
                map.put("satis", 0);
                map.put("satisfaction", "0.00%");
            } else { // 格式化满意度
                double satisfaction = Double.parseDouble(map.get("satisfaction").toString()) * 100.00;
                map.put("satis", satisfaction);
                map.put("satisfaction", String.format("%.2f%%", satisfaction));
            }
        }

        if (hasServiceOptions) {
            Map<String, Object> resultMap = new HashMap<>();
            List<String> collect = mydOptionsList.stream().distinct().collect(Collectors.toList());
            Map<String, Map<String, Integer>> totalMap = new HashMap<>();
            for (int i = 0; i < collect.size(); i++) {
                totalMap.put(collect.get(i), new HashMap<>());
            }
            //总满意度分值
            double totalScore = 0;
            //总问卷数量
            int totalNum = 0;
            for (int i = 0; i < resultList.size(); i++) {
                totalNum += (Integer) resultList.get(i).get("totalNum");
                // 遍历所有分别统计的Map
                for (Map.Entry<String, Object> entry : resultList.get(i).entrySet()) {
                    if (entry.getValue() instanceof Map) {
                        // 获取当前Map的key值，即满意度
                        String key = entry.getKey();
                        // 获取当前Map中的value值，即满意度对应的各项统计数据
                        Map<String, Integer> valueMap = (Map<String, Integer>) entry.getValue();
                        // 遍历当前Map中的每一个键值对
                        for (Map.Entry<String, Integer> subEntry : valueMap.entrySet()) {
                            // 获取当前键值对的key值，即各项统计数据的名称
                            String subKey = subEntry.getKey();
                            // 获取当前键值对的value值，即各项统计数据的数量
                            int subValue = subEntry.getValue();
                            // 如果合计的Map中当前的key值和subKey值都不存在，则新建一个键值对
                            totalMap.get(key).putIfAbsent(subKey, 0);
                            // 将当前键值对的value值加入到合计的Map中对应的键值对的value中
                            totalMap.get(key).put(subKey, totalMap.get(key).get(subKey) + subValue);
                        }
                    }
                }
                Map<String, Object> map1 = resultList.get(i);
                int satisfactionWeight = (Integer) resultList.get(i).get("satisfactionWeight");
                for (String key : map1.keySet()) {
                    if ("未接触".equals(key)) {
                        continue;
                    }
                    //如果是满意度选项
                    if (satisfactionScoreMap.containsKey(key)) {
                        int satisfactionScore = satisfactionScoreMap.get(key);
                        //如果有服务选项
                        Map<String, Object> map = (Map<String, Object>) map1.get(key);
                        totalScore += (Integer) map.get("总数量") * satisfactionScore * satisfactionWeight;
                    }
                }
            }
            double satisfaction = totalScore / totalNum / 5;
            resultMap.put("name", "合计");
            if (totalNum == 0) {
                resultMap.put("satisfaction", "0.00%");
            } else { // 格式化满意度
                resultMap.put("satisfaction", String.format("%.2f%%", satisfaction));
            }
            resultMap.putAll(totalMap);
            resultList.add(resultMap);
        } else {
            // 合计
            List<Map<String, Object>> resultAllList = new ArrayList<>(resultList);
            Map<String, Object> resultMap = new HashMap<>();
            //总满意度分值
            double totalScore = 0;
            //总问卷数量
            int totalNum = 0;

            //int satisfactionWeightAll = 0;
            for (int i = 0; i < resultAllList.size(); i++) {
                // int satisfactionWeight = (Integer) resultAllList.get(i).get("satisfactionWeight");
                // totalNum += (Integer) resultAllList.get(i).get("totalNum");
                Map<String, Object> map = resultAllList.get(i);
                for (Map.Entry<String, Object> entry : map.entrySet()) {
                    String key = entry.getKey();
                    if (entry.getValue() instanceof Integer) {
                        Integer value = (Integer) entry.getValue();
                        if (resultMap.containsKey(key)) {
                            resultMap.put(key, (Integer) resultMap.get(key) + value);
                        } else {
                            resultMap.put(key, value);
                        }
                    }
                }
                for (String key : map.keySet()) {
                    if ("未接触".equals(key)) {
                        continue;
                    }
                    if (satisfactionScoreMap.containsKey(key)) {
                        int satisfactionScore = satisfactionScoreMap.get(key);
                        //如果有服务选项
                        totalScore += (Integer) map.get(key) * satisfactionScore;
                        totalNum += (Integer) map.get(key);
                    }
                }
            }
            double satisfaction = totalScore / totalNum / 5;
            resultMap.put("name", "合计");
            if (totalNum == 0) {
                resultMap.put("satisfaction", "0.00%");
            } else { // 格式化满意度
                resultMap.put("satisfaction", String.format("%.2f%%", satisfaction * 100));
            }
            resultList.add(resultMap);
        }
        return resultList;
    }
}
